// 01.数组扁平化
const arr = [1, [2, [3, [4, 5]]], 6];
// => [1, 2, 3, 4, 5, 6]

console.log(arr.flat(Infinity));
// 正则方式
console.log(JSON.stringify(arr).replace(/\[|\]/g, '').split(','));
console.log(JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']'));
// reduce方式
const flatten = (arr) => {
	return arr.reduce((pre, cur) => {
		return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
	}, []);
};
// 指定深度
const flattenWithDepth = (arr, depth = 1) => {
	return arr.reduce((pre, cur) => {
		return pre.concat(depth > 1 && Array.isArray(cur) ? flatten(cur, depth - 1) : cur);
	}, []);
};

console.log(flatten(arr));
console.log(flattenWithDepth(arr));

// 递归方式
const diguifn = function (target) {
    const diguiResult = []
    const fn = (arr) => {
        arr.forEach(item => {
            if (Array.isArray(item)) {
                fn(item)
            } else {
                diguiResult.push(item)
            }
        });
    }
    fn(target)
    return diguiResult
}
console.log(diguifn(arr));

const diguifn2 = function (arr) {
    let diguiResult = []
    arr.forEach(item => {
        if (Array.isArray(item)) {
            diguiResult = diguiResult.concat(diguifn2(item))
        } else {
            diguiResult.push(item)
        }
    });
    return diguiResult
}
console.log('digui2',diguifn2(arr));
// 用 map
const deepFlatten = (arr) => [].concat(...arr.map((v) => (Array.isArray(v) ? deepFlatten(v) : v)));
console.log(deepFlatten(arr));
